package com.cjyd.hrjb.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cjyd.hrjb.exception.ServiceException;
import com.cjyd.hrjb.model.dto.VerifyCodeDto;
import com.cjyd.hrjb.service.VerifyCodeService;
import com.cjyd.hrjb.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * Created fei wo by 2020/3/27
 */
@Slf4j
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    private static final String VERIFY_CODE_REDIS_KEY = "admin:login:verify:%s";

    private StringRedisTemplate stringRedisTemplate;

    public VerifyCodeServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public VerifyCodeDto verifyPicBase64(String flag) {
        if (!StringUtils.isEmpty(flag)) {
            Boolean hasKey = stringRedisTemplate.hasKey(String.format(VERIFY_CODE_REDIS_KEY, flag));
            if (hasKey != null && hasKey){
                Boolean delete = stringRedisTemplate.delete(String.format(VERIFY_CODE_REDIS_KEY, flag));
                if (delete == null || !delete) {
                    log.warn("【清除验证码失败】");
                }
            }
        }
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 60);
        String imageBase64 = lineCaptcha.getImageBase64();
        String uuid = IdUtil.simpleUUID();
        VerifyCodeDto verifyCodeDto = new VerifyCodeDto();
        verifyCodeDto.setFlag(uuid);
        verifyCodeDto.setPicBase64(imageBase64);

        stringRedisTemplate.opsForValue().set(String.format(VERIFY_CODE_REDIS_KEY, uuid), lineCaptcha.getCode(), Duration.ofSeconds(60));
        return verifyCodeDto;
    }

    @Override
    public void verifyCode(String code, String flag) {
        Boolean hasKey = stringRedisTemplate.hasKey(String.format(VERIFY_CODE_REDIS_KEY, flag));
        if (hasKey == null || !hasKey) throw new ServiceException(ResultCode.VERIFY_CODE_EXPIRED);

        String cacheCode = stringRedisTemplate.opsForValue().get(String.format(VERIFY_CODE_REDIS_KEY, flag));
        if (!ObjectUtil.equal(cacheCode, code))  throw new ServiceException(ResultCode.VERIFY_CODE_FAIL);
    }
}
